package com.huike.report.service.impl;

import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.domain.vo.LineChartVo;
import com.huike.clues.mapper.*;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.domain.vo.*;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;
    
    @Autowired
    private ReportMapper reportMpper;



    /**
     * 渠道统计
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.chanelStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("channel");
            String lable=  sysDictDataMapper.selectDictLabel("clues_item",subjectValue);
            datum.put("channel",lable);
        }
        return data;
    }

    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
       return contractMapper.selectTbContractList(tbContract);
    }


    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.activityStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId= (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if(tbActivity==null){
                datum.put("activity", "其他");
            }else{
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 按照部门统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.deptStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId= (Long) datum.get("dept_id");
            if(deptId!=null){
                SysDept dept= deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 按照渠道统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.channelStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("channel");
            if(subjectValue!=null){
                String lable=  sysDictDataMapper.selectDictLabel("clues_item",subjectValue);
                datum.put("channel",lable);
            }
        }
        return data;
    }


    /**
     * 按照归属人统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
       return  contractMapper.ownerShipStatistics(beginCreateTime,endCreateTime);
    }


    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities= activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list=new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if(clueCount.get("falseClues")!=null){
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if(contractCount.get("amount")==null) {
                	dto.setAmount(0d);
                }else {
                	dto.setAmount((Double) contractCount.get("amount"));
                }
                if(contractCount.get("cost")==null) {
                	dto.setCost(0d);
                }else {
                	dto.setCost((Double) contractCount.get("cost"));
                }
                
            }
            list.add(dto);
        }
        return list;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId= request.getDeptId();
        TbAssignRecord tbAssignRecord=new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }


    /**
     * 获取首页基本数据
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        // 2.2 开始查询第一个属性 线索数量
        result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
        // 2.3 开始查询第一个属性 商机数量
        result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
        // 2.4 开始查询第一个属性 合同数量
        result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
        //5 返回结果集对象
        return result;
    }

    /**
     * 首页今日简报
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexTodayInfoVO getTodayInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexTodayInfoVO result = new IndexTodayInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        //获取当天时间
         Date now=new Date();
        // 2.2 开始查询第一个属性 线索数量
        result.setTodayCluesNum(reportMpper.getTodatCluesNum(beginCreateTime,endCreateTime,username,now));
        // 2.3 开始查询第一个属性 商机数量
        result.setTodayBusinessNum(reportMpper.getTodatbusinessNum(beginCreateTime,endCreateTime,username,now));
        // 2.4 开始查询第一个属性 合同数量
        result.setTodayContractNum(reportMpper.getTodatContractNum(beginCreateTime,endCreateTime,username,now));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setTodaySalesAmount(reportMpper.getTodatSalesAmount(beginCreateTime,endCreateTime,username,now));


        return result;
    }

    /**
     * 首页待跟进数据展示
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexTodoInfoVO getTodoInfo(String beginCreateTime, String endCreateTime) {

        //1 构建一个空的结果集对象
        IndexTodoInfoVO result = new IndexTodoInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();

        // 2.2 开始查询第一个属性 线索数量
        result.setTofollowedCluesNum(reportMpper.getTofollowedCluesNum(beginCreateTime,endCreateTime,username));
        // 2.3 开始查询第一个属性 商机数量
        result.setTofollowedBusinessNum(reportMpper.getTofollowedBusinessNum(beginCreateTime,endCreateTime,username));
        // 2.4 开始查询第一个属性 合同数量
        result.setToallocatedCluesNum(reportMpper.getToallocatedCluesNum(beginCreateTime,endCreateTime,username));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setToallocatedBusinessNum(reportMpper.getToallocatedBusinessNum(beginCreateTime,endCreateTime,username));

        return result;
    }

    @Override
    public List<SubjectStatisticsVo> getSubjectStatistics(String beginCreateTime, String endCreateTime) {
        List<SubjectStatisticsVo> contractNumAndSubject = reportMpper.getContractNumAndSubject(beginCreateTime, endCreateTime);
        for (SubjectStatisticsVo subjectStatisticsVo : contractNumAndSubject) {
            String name = reportMpper.selectNameBySubjicet(subjectStatisticsVo.getSubject());
            subjectStatisticsVo.setSubject(name);
        }
        return  contractNumAndSubject;
    }

    /**
     * 有效线索数
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public VulnerabilityMapVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        return reportMpper.getVulnerabilityMap(beginCreateTime,endCreateTime);
    }

    /**
     * 商机转化数量
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<BusinessChangeStatisticsVo> getbusinessChangeStatistics(String beginCreateTime, String endCreateTime) {
        //得到转化数量
        List<BusinessChangeStatisticsVo> businessChangeStatisticsVos = reportMpper.getbusinessChangeStatistics(beginCreateTime, endCreateTime);
        //得到所用商机，计算转化率
        Integer totalBusinessNum = reportMpper.getTotalBusinessNum(beginCreateTime, endCreateTime);
        for (BusinessChangeStatisticsVo businessChangeStatisticsVo : businessChangeStatisticsVos) {
            Double radio = businessChangeStatisticsVo.getRadio();
            Integer num = businessChangeStatisticsVo.getNum();//转化数量
            radio= Double.valueOf(num)/totalBusinessNum;
            radio=(double)Math.round(radio*100)/100;
            businessChangeStatisticsVo.setRadio(radio);
        }
        return businessChangeStatisticsVos;
    }

    /**
     * 线索转化商机数量
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<SalesStatisticVo> getSalesStatistic(String beginCreateTime, String endCreateTime) {
        //获取线索转换商机数量集合
        List<SalesStatisticVo> salesStatistices = reportMpper.getSalesStatistic(beginCreateTime, endCreateTime);
        //获取所有线索
        Integer clueNum = reportMpper.getClueNum(beginCreateTime, endCreateTime);
        //计算装换率
        for (SalesStatisticVo salesStatisticVo : salesStatistices) {
            //初始化转换率
            Double radio = salesStatisticVo.getRadio();
            radio=Double.valueOf(salesStatisticVo.getNum())/clueNum;
            radio=(double)Math.round(radio*100)/100;
            salesStatisticVo.setRadio(radio);
        }

        return salesStatistices;
    }

    /**
     * 获取每天新增的线索数量
     *
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public LineChartVo1 getClueNumAndDate(String beginCreateTime, String endCreateTime) {

        LineChartVo1 lineChartVo=null;
        try {
            //1.获取时间范围内的每一天
            List<String> dates = findDates(beginCreateTime, endCreateTime);
             lineChartVo = new LineChartVo1();
            lineChartVo.setXAxis(dates);
            //2.封装每天新增线索量
            List<Map<String, Object>> clueNumAndDate = reportMpper.getClueNumAndDate(beginCreateTime, endCreateTime);
            LineSeriesVo1 lineSeriesVo1 = new LineSeriesVo1();
            ArrayList<Integer> data1 = new ArrayList<>();
            ArrayList<Integer> data2 = new ArrayList<>();

            lineSeriesVo1.setName("新增线索数量");

            LineSeriesVo1 lineSeriesVo2 = new LineSeriesVo1();
            lineSeriesVo2.setName("线索总数量");

            int sum = 0;
            for (String s : dates) {
                Optional optional=  clueNumAndDate.stream().filter(d->d.get("dd").equals(s)).findFirst();
                if(optional.isPresent()){
                    Map<String,Object> cuurentData=  (Map<String,Object>)optional.get();
                    data1.add((Integer) cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                }else{
                    data1.add(0);
                }
                data2.add(sum);
            }
//            Integer sum=0;
//            for (String date : dates) {
//                for (Map<String, Object> stringObjectMap : clueNumAndDate) {
//                    if (stringObjectMap.get("dd").equals(date)){
//                        Integer num = (Integer) stringObjectMap.get("num");
//                        sum+=num;
//                        data1.add(num);
//                        data2.add(sum);
//                    }else {
//                        data1.add(0);
//                        data2.add(sum+0);
//                    }
//                }
//
//            }

//            for (Map<String, Object> stringObjectMap : clueNumAndDate) {
//
//                Integer num = (Integer) stringObjectMap.get("num");
//                if (num!=null){
//                    sum+=num;
//                    data1.add(num);
//                    data2.add(sum);
//                }else {
//                    data1.add(0);
//                    data2.add(sum+0);
//                }
//
//            }
           List<LineSeriesVo1> series = new ArrayList<>();
            lineSeriesVo1.setData(data1);
            lineSeriesVo2.setData(data2);
            series.add(lineSeriesVo1);
            series.add(lineSeriesVo2);
            lineChartVo.setSeries(series);



        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lineChartVo;
    }

    /**
     * 获取时间范围内的每一天
     * @param beginTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static List<String> findDates(String beginTime, String endTime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


}